package com.zlsy.thread.threadsafe;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author zhouliang
 * @date 2020/03/19
 * <p>
 * 手写一个必然发生死锁的列子
 * <p>
 * 注意：
 * static final Object lock1 = new Object(); lock1放在公有的内存中，所有的实列拿到的都是同一把锁
 * <p>
 * final Object lock1 = new Object(); 私有属性 不同的对象lock是不同的锁
 **/
@Slf4j
public class DeadlockThread implements Runnable {

    private int flag;
    static final Object lock1 = new Object();
    static final Object lock2 = new Object();

    public DeadlockThread(int flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        System.err.println(flag);
        if (flag == 1) {
            synchronized (lock1) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    log.info("当前的flag为:{}", flag);
                }
            }
        }
        if (flag == 2) {
            synchronized (lock2) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    log.info("当前的flag为:{}", flag);
                }
            }
        }
    }

    public static void main(String[] args) {
        DeadlockThread instance1 = new DeadlockThread(1);
        DeadlockThread instance2 = new DeadlockThread(2);

        Thread thread = new Thread(instance1);
        Thread thread1 = new Thread(instance2);
        thread.start();
        thread1.start();
    }
}
